import Store from '@/store'
import dayjs from 'dayjs'
import duration from "dayjs/plugin/duration";
dayjs.extend(duration); // 使用插件
dayjs.locale("zh-cn"); // 使用本地化语言

// 格式化时间
export function formatDate(time, flag) {
  var date = new Date(time);
  var fmt = flag ? 'yyyy-MM-dd HH:mm:ss' : 'yyyy-MM-dd';
  var o = {
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    S: date.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ?
        o[k] :
        ("00" + o[k]).substr(("" + o[k]).length)
      );
  return fmt;
}

// 获取时间差
export const timeDiff = (startTime, endTime) => {
  const diffDays = dayjs(endTime).diff(dayjs(startTime)) / (24 * 60 * 60 * 1000)
  return diffDays
}

// select 获取name值
export const getPropName = (value, opts = [], label="label", prop="id") => {
  let name = null
  let obj = opts.find(e => e[prop] == value)
  name = obj && obj[label]
  return name
}

// select 获取name值
export const getSexDesc = (value) => {
  if(value == 1) {
    return '男'
  } else if(value == 2) {
    return '女'
  } else {
    return ''
  }
}

/**
 * 函数防抖 (只执行最后一次点击)
 * @param fn
 * @param delay
 * @returns {Function}
 * @constructor
 */
export const Debounce = (fn, t) => {
  let delay = t || 500;
  let timer;
  return function () {
    let args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      timer = null;
      fn.apply(this, args);
    }, delay);
  };
};


/**
 * 函数节流
 * @param fn
 * @param interval
 * @returns {Function}
 * @constructor
 */
export const Throttle = (func, wait, trailing) => {
  let timer = null
  let start = 0
  return function () {
      let now = new Date()
      // 拦截：延迟时间>多次点击间隔时间，执行：多次点击间隔时间>延迟时间
      if ((now - start) >= wait) {
          // 由于setTimeout存在最小时间精度问题，因此会存在到达wait的时间间隔
          // 但之前设置的setTimeout操作还没被执行，因此为保险起见，这里先清理setTimeout操作
          timer && clearTimeout(timer)
          timer = null
          start = now
          return func()
      } else if (!timer && trailing) {
          // trailing有值时，延时执行func函数
          // 频繁操作，第一次设置定时器之后，之后的不会再走到这里创建定时器
          // 清除问题，只能在第二有效点击的时候才会清除
          timer = setTimeout(() => {
              timer = null
              return func
          }, wait)
      }
  }
};


/**
 * 身份证解析
 * @param idCard
 * @returns {sex, peBirthday, age}
 * @constructor
 */
export const analyzeIDCard = (idCard) => {
  if(!idCard || typeof idCard != 'string') {
    return 
  }
  var sexAndAge = {};
  // let lv1 = idCard.substr(0, 2);
  // let lv2 = idCard.substr(0, 4);
 //获取性别
  if (parseInt(idCard.substr(16, 1)) % 2 == 1) {
    sexAndAge.sex = "1";
  } else if(parseInt(idCard.substr(16, 1)) % 2 == 0) {
    sexAndAge.sex = "2";
  }
  //获取出生年月日
  //userCard.substring(6,10) + "-" + userCard.substring(10,12) + "-" + userCard.substring(12,14);
  var yearBirth = idCard.substring(6, 10);
  var monthBirth = idCard.substring(10, 12);
  var dayBirth = idCard.substring(12, 14);
  //得到年龄
  sexAndAge.peBirthday = `${yearBirth}-${monthBirth}-${dayBirth}`;
  //获取当前年月日并计算年龄
  var myDate = new Date();
  var monthNow = myDate.getMonth() + 1;
  var dayNow = myDate.getDate();
  var age = myDate.getFullYear() - yearBirth;
  if (monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)) {
    age--;
  }
  sexAndAge.age = !isNaN(age) ? age : '';
  return sexAndAge;
}

// 行内需要px转rem
export const pxtorem = function(px){
  if(!px) {
    return false
  } else {
    if(/%/ig.test(px)){ // 有百分号%，特殊处理，表述pc是一个有百分号的数，比如：90%
      return px
    }else{
      return (parseFloat(px) / 100 ) + 'rem'
    }
  }
}

// 只能输入正整数
export function limitInt(target, name) {
  if (target[name] && typeof(target[name]) == Number) {
      if (!target[name]) return
      let str = target[name] + '';
      target[name] = parseInt(str.replace(/[^0-9]/g, ""));
      this.$set(target, name, target[name])
  } else {
      let str = target[name] + '';
      target[name] = str.replace(/[^0-9]/g, "");
  }

}

// 缩放
export const echartsPx = function(val){
  const baseSize = 100
  const baseScale = baseSize / 1920
  const widthScale = window.innerWidth < 1366 ?  1366 : window.innerWidth
  const rem = widthScale * baseScale / 100 * val
  return rem
}

// 限制输入小数，整数
export const inputNum = function(e, form, key, isFloat) {
  if (isFloat) {
    e.target.value = e.target.value.match(/\d+\.?\d{0,2}/, "");
  } else {
    e.target.value = e.target.value.replace(/[^\d]/g, "");
  }
  this.$set(form, key, e.target.value)
}

// 小写转大写
export const changeNumToHan = function(num) {
  var arr1 = new Array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
  var arr2 = new Array('', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千', '亿');//可继续追加更高位转换值
  if (!num || isNaN(num)) {
    return "零";
  }
  var english = num.toString().split("");
  var result = "";
  for (var i = 0; i < english.length; i++) {
    var des_i = english.length - 1 - i;//倒序排列设值
    result = arr2[i] + result;
    var arr1_index = english[des_i];
    result = arr1[arr1_index] + result;
  }
  //将【零千、零百】换成【零】 【十零】换成【十】
  result = result.replace(/零(千|百|十)/g, '零').replace(/十零/g, '十');
  //合并中间多个零为一个零
  result = result.replace(/零+/g, '零');
  //将【零亿】换成【亿】【零万】换成【万】
  result = result.replace(/零亿/g, '亿').replace(/零万/g, '万');
  //将【亿万】换成【亿】
  result = result.replace(/亿万/g, '亿');
  //移除末尾的零
  result = result.replace(/零+$/, '');
  //将【零一十】换成【零十】
  //result = result.replace(/零一十/g, '零十');//貌似正规读法是零一十
  //将【一十】换成【十】
  result = result.replace(/^一十/g, '十');
  return result;
}

// 权限值，返回true || false
export const hasPermission = function(value){
  let permissionList = Store.getters.permissionList;
  const permissionRoles = value;
  const permissionBoolean = permissionList.some(role => {
      return permissionRoles === role;
  })
  return permissionBoolean
}


// 数据权限
export const hasDataPermission = function(operatePermissionList, permissionValue){
  if(operatePermissionList) {
    let list = operatePermissionList
    let obj = list.find(e => e.scope === permissionValue)
    return obj ? obj.operatePermission : false
  } else {
    return true
  }
}

export const getImageUrl = function(value) {
  let href = new URL(value, import.meta.url).href
  return href
}